package com.bruce.shop.web.front;

import com.alibaba.fastjson.JSON;
import com.bruce.shop.commons.constans.ShopConstants;
import com.bruce.shop.commons.utils.Response;
import com.bruce.shop.commons.web.DispatcherServlet;
import com.bruce.shop.entity.User;
import com.bruce.shop.service.UserService;
import com.bruce.shop.service.impl.UserServiceImpl;
import com.sun.org.apache.bcel.internal.classfile.Code;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @author BruceXia
 * @version 1.0.0
 * @description:SSO:单点登录，我们把用户认证(登录，注册，注销，修改密码，激活。。)的相关的操作全部放这
 * @date 2022/9/2110:47
 */
@WebServlet("/SSOController/*")
public class SSOController extends DispatcherServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 根据前端ajax传入的用户信息调用业务层方法注册用户之后响应给前端
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */

    public String loginUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //从域中获取Ajax传入的json字符串
        String json=request.getReader().readLine();
        System.out.println(json);
        //将json字符串转成user对象
        User user=JSON.parseObject(json,User.class);

        //将用户名和密码传入service层进行判断，得到一个结果
        Map<String,Object> result=userService.loginUser(user.getUsername(),user.getPass());
        if ((Integer) result.get("code")==200){
            //若返回的结果map中的code为200，则把map中的data也就是user账号信息存入session中
            request.getSession().setAttribute("user",result.get("data"));

        }
        //若result有值则说明数据传输成功了，将返回的结果响应给前端
        return ShopConstants.JSON+":"+ JSON.toJSONString(result);
    }


    public String registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //从请求体获取前端Ajax传入的user对象的json数据
        String json = request.getReader().readLine();
        //把json字符串转成user对象
        User user = JSON.parseObject(json, User.class);
        //响应给前端json数据
        return ShopConstants.JSON + ":" + Response.outJSON(userService.register(user));
    }

    /**
     * 激活用户，本质就是修改用户的状态
     * @param request
     * @param response
     * @return
     */
    public void activeUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户网页传入的激活码
        String code = request.getParameter("code");
        //将激活码传入service层调用方法进行激活
        Integer integer = userService.activeUser(code);
        if (integer > 0) {
            //激活成功！响应给浏览器一个链接让用户点击跳转到登录页面;
            response.getWriter().write("账户激活成功！点击这里登录<a href='http://localhost:8080/login.jsp'>登录</a>");
        }else{
            response.getWriter().write("激活失败！");
        }

    }
}
